Collision disturbing the jumping mechanic in java 2D game [on hold]
Posted
by
user50931
on Game Development
See other posts from Game Development
or by user50931
Published on 2014-08-24T14:59:15Z
Indexed on
2014/08/24
16:29 UTC
Read the original article
Hit count: 208
So I have been working on a 2D Java game recently and everything was going smoothly, until I reached a problem to do with the players jumping mechanic. So far I've got the player to jump a fixed rate and fall due to gravity.
Hers my code for my Player class.
public class Player extends GameObject {
public Player(int x, int y, int width, int height, ObjectId id) {
super(x, y, width, height, id);
}
@Override
public void tick(ArrayList<GameObject> object) {
if(go){
x+=vx;
y+=vy;
}
if(vx <0){
facing =-1;
}else if(vx >0)
facing =1;
checkCollision(object);
checkStance();
}
private void checkStance() {
if(falling){ //gravity
jumping = false;
vy = speed/2;
}
if(jumping){ // Calculates how high jump should be
vy = -speed*2;
if(jumpY - y >= maxJumpHeight)
falling =true;
}
}
private void checkCollision(ArrayList<GameObject> object) {
for(int i=0; i< object.size(); i++ ){
GameObject tempObject = object.get(i);
if(tempObject.getId() == ObjectId.Ledge){
if(getBoundsTop().intersects(tempObject.getBoundsAll())){ //Top
y = tempObject.getY() + tempObject.getBoundsAll().height;
falling =true;
}
if(getBoundsRight().intersects(tempObject.getBoundsAll())){ // Right
x = tempObject.getX() -width ;
}
if(getBoundsLeft().intersects(tempObject.getBoundsAll())){ //Left
x = tempObject.getX() + tempObject.getWidth();
}
if(getBoundsBottom().intersects(tempObject.getBoundsAll())){ //Bottom
y = tempObject.getY() - height;
falling =false;
vy=0;
}else{
falling =true;
}
}
}
}
@Override
public void render(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect((int)x, (int)y, width, height);
}
@Override
public Rectangle getBoundsAll() {
return new Rectangle((int)x, (int)y,width,height);
}
public Rectangle getBoundsTop() {
return new Rectangle((int) x , (int)y ,width,height/15);
}
public Rectangle getBoundsBottom() {
return new Rectangle( (int)x , (int) y +height -(height /15),width,height/15);
}
public Rectangle getBoundsLeft() {
return new Rectangle( (int) x , (int) y + height /10 ,width/8,height - (height /5));
}
public Rectangle getBoundsRight() {
return new Rectangle((int) x + width - (width/8) ,(int) y + height /10 ,width/8,height - height/5);
}
}
My problem is when I add:
else{ falling =true; }
during the loop of the ArrayList to check collision, it stops the player from jumping and keeps him on the ground. I've tried to find a way around this but haven't had any luck. Any suggestions?
© Game Development or respective owner